package com.andy.service.impl;

import cn.hutool.core.date.DateUtil;
import com.andy.infrastructure.util.FileUtil;
import com.andy.infrastructure.util.FreeMarkerUtil;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AbiCreateDaoService {

    @Autowired
    private freemarker.template.Configuration cfg;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private FreeMarkerUtil freeMarkerUtil;

    private static final String TOTLE_FILE_PATH = "D:\\autoOutput";

    private final Map<String,String> sqlType = new HashMap<String,String>(){
        {
            put("bigint", "Long");
            put("smallint", "Integer");
            put("int", "Integer");
            put("tinyint", "Integer");
            put("bit", "Integer");
            put("varchar", "String");
            put("json", "String");
            put("char", "String");
            put("text", "String");
            put("longtext", "String");
            put("datetime", "LocalDateTime");
            put("timestamp", "LocalDateTime");
            put("date", "Date");
            put("decimal", "BigDecimal");
        }
    };


    public void createDao(String input){
        Map<String, Object> map = getDbMap(input);
        //生成entity
        createEntity(map);
        //生成mapper接口
        createMapperInterface(map);
        //生成mapper.xml
        createMapperXml(map);

        //弹出框体
        FileUtil.popupDir(TOTLE_FILE_PATH);
    }

    public Map<String, Object> getDbMap(String input){
        Connection conn = null;
        Map<String, Object> map = null;
        try{
            //拆解入参
            map =  freeMarkerUtil.putInput(input);
            String tableName = (String)map.get("tableName");
            conn = dataSource.getConnection();
            Statement stmt = conn.createStatement();

            //1-整理字段数据
            List<Map<String, Object>> columnList = new ArrayList <>();
            //字段名、描述、类型
            ResultSet rsFields = stmt.executeQuery(" show full fields from " + tableName + "");
            for (; rsFields.next();) {
                Map<String,Object> tempMap = new HashMap <>();
                tempMap.put("columnName",rsFields.getString("FIELD"));
                tempMap.put("columnComment",rsFields.getString("COMMENT"));
                //类型：varchar(60) int(11) 这样子的，需要把括弧去掉
                String type = rsFields.getString("type");
                if(type.indexOf("(")>0){
                    type = type.substring(0,type.indexOf("("));
                }
                tempMap.put("columnType",sqlType.get(type));
                //增强大小写形式
                tempMap = freeMarkerUtil.advanceMapCase(tempMap);
                //放入列表
                columnList.add(tempMap);
            }
            //放入大map中
            map.put("columnList",columnList);

            //2-整理表数据
            ResultSet rstComment=stmt.executeQuery("SHOW CREATE TABLE "+tableName);
            for (; rstComment.next();) {
                String tableComment = rstComment.getString(2).substring(rstComment.getString(2).lastIndexOf("COMMENT")+9,rstComment.getString(2).length()-1);
                map.put("tableComment", tableComment);
                break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return map;
    }

    /**
     * 生成po文件
     * @param map
     */
    private void createEntity(Map<String, Object> map){
        //模板生成vo字符串
        String ftlName = "abi_entity.ftl";
        Template t = null;
        try {
            t = cfg.getTemplate(ftlName);
            // 输出到控制台
            StringWriter writer = new StringWriter();
            t.process(map, writer);
            String poStr = writer.toString();

            //生成文件
            String filePath = TOTLE_FILE_PATH + "\\entity";
            String fileName = (String)map.get("tableName_Iii")+".java";
            //创建文件
            FileUtil.createFile(fileName,poStr,filePath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成mapper接口文件
     * @param map
     */
    private void createMapperInterface(Map<String, Object> map){
        //模板生成vo字符串
        String ftlName = "abi_mapper_class.ftl";
        Template t = null;
        try {
            t = cfg.getTemplate(ftlName);
            // 输出到控制台
            StringWriter writer = new StringWriter();
            t.process(map, writer);
            String poStr = writer.toString();

            //生成文件
            String filePath = TOTLE_FILE_PATH + "\\mapper";
            String fileName = (String)map.get("tableName_Iii")+"Mapper.java";
            //创建文件
            FileUtil.createFile(fileName,poStr,filePath);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成mapper.xml文件
     * @param map
     */
    private void createMapperXml(Map<String, Object> map){
        //模板生成vo字符串
        String ftlName = "abi_mapper_xml.ftl";
        Template t = null;
        try {
            t = cfg.getTemplate(ftlName);
            // 输出到控制台
            StringWriter writer = new StringWriter();
            t.process(map, writer);
            String poStr = writer.toString();

            //生成文件
            String filePath = TOTLE_FILE_PATH + "\\xml";
            String fileName = (String)map.get("tableName_Iii")+"Mapper.xml";
            //创建文件
            FileUtil.createFile(fileName,poStr,filePath);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 临时的白名单方案
     * @param input
     * @return
     */
    public void createTempWhiteList(String input){
        StringBuffer sb = new StringBuffer();

        String[] inputLineArr = input.split("\n");
        String appName = inputLineArr[0];
        String currentTime = DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
        for(int i=1;i<inputLineArr.length;i++){
            String mobile = inputLineArr[i];
            sb.append(createTempSql(appName,mobile,currentTime));
            sb.append("\n");
        }

        //生成文件
        String fileName = "whiteSql_"+DateUtil.format(LocalDateTime.now(),"yyyyMMdd HHmmss")+".java";
        String filePath = "D:\\autoOutput\\whiteSql";
        //创建文件
        try {
            FileUtil.createFile(fileName,sb.toString(),filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileUtil.popupDir(TOTLE_FILE_PATH);
    }

    /**
     *
     * @param appName
     * @param mobile
     * @param currentTime   2021-08-11 14:24:04
     * @return
     */
    private String createTempSql(String appName,String mobile,String currentTime){
        String listId = "";
        String appId = "";
        if("百威".equals(appName)){
            listId = "6";
            appId = "budspace";
        }else if("哈啤".equals(appName)){
            listId = "7";
            appId = "hpcommunity";
        }

        String sql = "insert into t_risk_black_white_list_detail (data_content, app_id, black_white_list_id, invalid_time, data_resource_type, valid, description, create_time, create_by, update_time, update_by, is_delete) select '"+mobile+"', '"+appId+"', "+listId+", NULL, 1, 1, '人工维护', '"+currentTime+"', NULL, '"+currentTime+"', NULL, 0 from `t_risk_black_white_list_detail` where not exists (select 1 from `t_risk_black_white_list_detail` where `app_id` ='"+appId+"' and `data_content` ='"+mobile+"') limit 1;";
        return sql;
    }



}
